<template>
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="value"
        v-imgError="defaultImg"
        :src="value"
        class="avatar"
        @click.stop.prevent="isShow = true"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-dialog :visible.sync="isShow" title="图片预览">
      <img :src="value" alt="" style="width: 100%">
    </el-dialog>
    <!-- 删除图片 -->
    <div v-if="value" class="del" @click.stop.prevent="del">x</div>
    <!-- 进度条 -->
    <transition name="fade">
      <el-progress v-if="isLoad" :percentage="percentage" />
    </transition>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      imageUrl: '',
      isShow: false,
      percentage: 0,
      isLoad: false,
      defaultImg: require('../../assets/common/head.jpg')
    }
  },
  methods: {
    del() {
      this.$emit('input', '')
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(res) {
      this.isLoad = true
      cos.putObject(
        {
          Bucket: 'hm77-1308947980' /* 必须：存储桶，使用自己注册的存储桶 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须，要求是字符串 */,
          StorageClass: 'STANDARD', // 固定，不用修改
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.isLoad = false
              }, 1000)
            }
          }
        },
        (err, data) => {
          // 上传成功的回调  err:代表错误，没有错误就代表成功  data：上传成功的接口返回值
          console.log(err || data)
          this.imageUrl = 'http://' + data.Location
          this.$emit('input', 'http://' + data.Location)
        }
      )
    }
  }
}
// 实例化
const cos = new COS({
  // 密钥
  SecretId: 'AKIDJSLxHK6bpmSrzpOghQs3xZuynMehTxA5',
  SecretKey: 'f5E6h02mFRO3RYPzHI2VgaDYcPv96mBJ'
})
// 4:使用
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadImg {
  width: 220px;
  position: relative;
  .del {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 50px;
    cursor: pointer;
  }
}
.fade-enter {
  opacity: 0;
}
.fade-leave-to {
  opacity: 0;
}
.fade-enter-active {
  transition: all 0.5s;
}
.fade-leave-active {
  transition: all 0.5s;
}
</style>
